<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { addQARApi } from '@/api/check/qar'
import { getQARTaskListApi, deleteQARTaskApi, addQARTaskApi, putQARTaskApi } from '@/api/check/task'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { ElInput, ElMessage, ElButton } from 'element-plus'
import { QARTaskType } from '@/api/check/task/types'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'

const ids = ref<string[] | number[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getQARTaskListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data,
      total: res.count
    }
  },
  fetchDelApi: async () => {
    const res = await deleteQARTaskApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    fixed: true,
    type: 'selection',
    width: 80,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'index',
    label: t('common.index'),
    type: 'index',
    width: 80,
    fixed: true,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'purchase_order',
    label: '订单号',
    minWidth: 120,
    fixed: true
  },
  {
    field: 'part_no',
    minWidth: 120,
    label: '零件/材料图号'
  },
  {
    field: 'part_name',
    minWidth: 120,
    label: '零件名称'
  },
  {
    field: 'material_no',
    minWidth: 120,
    label: '物料号'
  },
  {
    field: 'product_type',
    minWidth: 120,
    label: '型号',
    search: {
      hidden: true
    }
  },
  {
    field: 'part_type',
    minWidth: 120,
    label: '零件/材料类型',
    search: {
      hidden: true
    }
  },
  {
    field: 'flight',
    minWidth: 120,
    label: '架次'
  },
  {
    field: 'vendor',
    label: '销售商',
    minWidth: 120,
    search: {
      hidden: true
    }
  },
  {
    field: 'zpm_cpm',
    label: 'ZPM/CPM',
    minWidth: 120,
    search: {
      hidden: true
    }
  },
  {
    field: 'size',
    label: '材料规格',
    minWidth: 120,
    search: {
      hidden: true
    }
  },
  {
    field: 'quantity_weight',
    label: '订货数量',
    minWidth: 120,
    search: {
      hidden: true
    }
  },
  {
    field: 'create_user',
    label: '创建人',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'create_datetime',
    label: '创建时间',
    minWidth: 180,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('common.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      minWidth: 100,
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElButton onClick={() => action(data.row, 'edit')}>编辑</ElButton>
              {/* <ElButton type="danger" onClick={() => delData(data.row)}>
                {t('common.del')}
              </ElButton> */}
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

// 生成QAR
const genQARLoading = ref(false)
const genQARDialog = ref(false)
const addQARItems = ref()

const genQARAction = async () => {
  const elTableExpose = await getElTableExpose()
  ids.value = elTableExpose?.getSelectionRows().map((v: QARTaskType) => v.id) || []
  addQARItems.value = elTableExpose?.getSelectionRows() || []
  if (ids.value.length > 0) genQARDialog.value = true
  else ElMessage.warning('未选择记录，无法生成QAR')
}

const genQARSave = async (type: string) => {
  genQARLoading.value = true
  try {
    const res = await addQARApi(type, addQARItems.value)
    if (res) {
      genQARDialog.value = false
      ElMessage.success(res.data)
      getList()
    }
  } finally {
    genQARLoading.value = false
  }
}

// QAR任务操作
const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<QARTaskType | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('common.add')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = 'add'
}

const delLoading = ref(false)

const delData = async (row: QARTaskType | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: QARTaskType) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: QARTaskType, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'common.edit' : 'common.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      const res =
        actionType.value === 'add' ? await addQARTaskApi(formData) : await putQARTaskApi(formData)
      if (res) {
        dialogVisible.value = false
        getList()
      }
    } finally {
      saveLoading.value = false
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton type="primary" @click="AddAction">{{ t('common.add') }}</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('common.del') }}
      </ElButton>
      <ElButton type="primary" @click="genQARAction">生成QAR</ElButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
      :fit="true"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="700px" max-height="500px">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :current-row="currentRow"
      :form-schema="allSchemas.formSchema"
    />

    <Detail
      v-if="actionType === 'detail'"
      :current-row="currentRow"
      :detail-schema="allSchemas.detailSchema"
    />

    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('common.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>

  <Dialog
    v-model="genQARDialog"
    title="生成QAR"
    width="500px"
    max-height="100px"
    :fullscreen="false"
  >
    <p>{{ `你选择了 ${ids.length} 条未生成QAR记录` }}</p>
    <template #footer>
      <ElButton type="primary" :loading="genQARLoading" @click="genQARSave('single')">
        单个生成QAR
      </ElButton>
      <ElButton
        type="primary"
        :loading="genQARLoading"
        @click="genQARSave('merge')"
        v-if="ids.length > 1"
      >
        合并生成QAR
      </ElButton>
      <ElButton @click="genQARDialog = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>
</template>
